import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import Skeleton from 'taro-skeleton'
import {ComponentClass} from 'react'
import {AtLoadMore, AtIcon} from 'taro-ui'
import {Image, ScrollView, Text, View, Swiper, SwiperItem, Block} from '@tarojs/components'
import {CityLocation} from '../utils/server.interface'
import {http} from '../utils/http'
import {
  LIMIT_FROM_SELLER_SINCE,
  MOVIE_CINEMAS, MOVIE_CITY,
  MOVIE_MOVIES,
  MOVIE_PLANS,
  RESOURCE_URL, SCAN_BIND_SELLER,
  SHARE_PIC
} from '../constants/api'
import {debounce, getHeadTop, GetRequest, setTempSellerId} from "../utils/tools";
import InfoHeaderBar from "./header-bar/info-header-bar";
import {user} from "../utils/user.service";
import {getMoviePoster} from "../utils/poster.service";
import {platform} from "../utils/platform-settting.service";
import {location} from "../utils/location.service";
import {h5Wx} from "../utils/h5.service";
import './info.scss'
import {lxH5Wx} from "../utils/lx.h5.service";

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  loadMoreStatus: "more" | "loading" | "noMore"
  searchKey: string
  movieList: any
  tempSellerId: any
  dateAry: any
  searchBarTop: number
  cinemaId: number
  movieId: number
  thisIndex: number
  tabsIndex: number
  planList: any
  planListLoad: boolean
  location?: any
  Ml?: any
  info: any
  imageUrl: string
  shareName: string
  isLogin: boolean
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Cinfo {
  props: IProps
}

class Cinfo extends Component {
  state: PageState = {
    isLogin: true,
    loadMoreStatus: 'loading',
    searchKey: '',
    tempSellerId: '',
    movieList: [],
    dateAry: [],
    searchBarTop: 0,
    cinemaId: 0,
    movieId: 0,
    planList: [],
    planListLoad: true,
    thisIndex: 0,
    tabsIndex: 0,
    info: {},
    imageUrl: '',
    shareName: ''
  }
  page = 1
  shareParams = ''

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 40) : (headTop.statusBar + headTop.top + 40)
    let showDay = 3
    const platformSet = await platform.getSetting()
    if (platformSet) {
      showDay = platformSet.movieDay || 3
    }
    this.setState({searchBarTop})
    let cinemaId = Taro.getCurrentInstance().router.params.id || 0
    let movieId = Taro.getCurrentInstance().router.params.mid || 0
    const scene = Taro.getCurrentInstance().router.params.scene as string | undefined;
    let bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    let tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    let bindSellerId = Taro.getStorageSync('bindSellerId') || 0;
    if (scene) {
      platform.scene = 0;
      const paramArr = scene.split('_');
      if (platformSet.isSellerPermanentLock) {
        if (!bindSellerId) {
          bindSellerId = paramArr[2];
        }
      } else {
        let id = paramArr[2]
        if (id && id.indexOf('name') > -1) {
          id = paramArr[2].split('name')[0]
        }
        bindSellerId = id;
      }
      if (paramArr[2]) {
        bindSellerIds = paramArr[2]
      }
      if (paramArr[3]) {
        tempSellerIds = paramArr[3]
      }
      cinemaId = paramArr[0];
      if (/^\S+_\d+_\d+_\d+$/.test(scene)) {
        movieId = paramArr[3];
        setTempSellerId(paramArr[3])
        this.setState({tempSellerId: paramArr[3]})
      }
    } else {
      if (platformSet.isSellerPermanentLock) {
        if (!bindSellerId) {
          bindSellerId = Taro.getCurrentInstance().router.params.bindSellerId || bindSellerId;
        }
      } else {
        bindSellerId = Taro.getCurrentInstance().router.params.bindSellerId || bindSellerId;
      }
    }
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, { temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds });
    }
    user.bindSellerId = bindSellerId
    Taro.setStorage({
      key: 'bindSellerId',
      data: user.bindSellerId,
    })
    if (bindSellerId) {
      Taro.login({
        success: (res) => {
          if (res.code) {
            const integralForm = {
              sellerId: bindSellerId,
              code: res.code
            }
            http.post(LIMIT_FROM_SELLER_SINCE, integralForm);
          } else {
            //console.log('登录失败！' + res.errMsg)
          }
        }
      })
    }
    const location = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
    const ML = Taro.getStorageSync("ML");
    if (location.region_id == 0 || location.region_id == undefined) {
      Taro.showLoading({title: "位置校正中"})
      this.getLocation(movieId, cinemaId)
    } else {
      const isLogin = await user.checkLogin()
      if (!isLogin) {
        this.setState({isLogin, location, ML, cinemaId, movieId})
        user.jumpLogin()
        return
      } else {
        this.setState({isLogin, location, ML, cinemaId, movieId})
      }
      await this.getInfo(cinemaId, location.region_id, ML)
      const ret = await this.getList(cinemaId, location.region_id, ML, movieId)
      if (ret) {
        let thisIndex = 0
        ret.movieList.map((item, index) => {
          if (item.std_id == movieId) {
            thisIndex = index
          }
        })
        if (process.env.TARO_ENV === "h5") {
          this.setState({
            movieList: ret.movieList,
          }, (res) => {
            this.showIndexH5(thisIndex)
          })
        } else {
          this.setState({
            movieList: ret.movieList,
            thisIndex
          })
        }

      }
    }
  }

  async componentDidShow() {
    const {isLogin, planListLoad} = this.state
    if (!isLogin) {
      const newIsLogin = await user.checkLogin()
      if (!newIsLogin) {
        this.setState({isLogin: newIsLogin})
        Taro.navigateBack({
          delta: 1
        })
        return
      }
      const {cinemaId, movieId, tabsIndex, dateAry, imageUrl, tempSellerId} = this.state
      if (!planListLoad) {
        await this.getData(cinemaId, movieId, dateAry[tabsIndex].paramDate)
      } else {
        const ML = Taro.getStorageSync("ML");
        const location = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
        await this.getInfo(cinemaId, location.region_id, ML)
        const ret = await this.getList(cinemaId, location.region_id, ML, movieId)
        if (ret) {
          let thisIndex = 0
          ret.movieList.map((item, index) => {
            if (item.std_id == movieId) {
              thisIndex = index
            }
          })
          this.setState({
            movieList: ret.movieList,
            thisIndex,
          })

        }
      }
      if (!imageUrl) {
        const res = await http.postCar(SHARE_PIC, {})
        if (res) {
          this.setState({
            imageUrl: res.sharePic,
            shareName: res.shortName,
          })
        }
        this.shareParams = await user.getSellerParams(tempSellerId)
      }
    }
  }

  async getInfo(cinemaId, cityId, ML) {
    const info = await http.MGet(MOVIE_CINEMAS, {cinemaId, cityId, lng: ML.lng, lat: ML.lat})
    if (info && info.cinemaList[0]) {
      this.setState({
        info: info.cinemaList[0]
      })
    }

  }

  async getList(cinemaId, cityId, ML, movieId) {
    const {thisIndex, tabsIndex} = this.state
    let data = {type: 1, cityId, lng: ML.lng, lat: ML.lat, cinemaId}
    if (movieId) {
      data = {type: 1, cityId, lng: ML.lng, lat: ML.lat, cinemaId, currentMovieId: movieId}
    }
    const list = await http.MGet(MOVIE_MOVIES, data)
    if (movieId) {
      if (list.dateList.length > 0) {
        this.getData(cinemaId, movieId, list.dateList[0].paramDate)
      } else {
        this.setState({planListLoad: false, loadMoreStatus: 'noMore',})
      }
    } else {
      if (list && list.movieList.length > 0 && list.movieList[thisIndex].std_id && list.dateList.length > 0) {
        this.getData(cinemaId, list.movieList[thisIndex].std_id, list.dateList[0].paramDate)
      } else {
        this.setState({planListLoad: false, loadMoreStatus: 'noMore',})
      }
    }
    this.setState({dateAry: list.dateList, tabsIndex: 0})
    return list
  }

  async getData(cinemaId, movieId?, startDate?) {
    // if(!this.state.planListLoad){
    //   Taro.showLoading({title:"加载中",mask:true})
    // }
    const list = await http.carGet(MOVIE_PLANS, {cinemaId, filmNo: movieId, startDate})
    // Taro.hideLoading()
    if (list) {
      this.setState({
        movieId,
        loadMoreStatus: 'noMore',
        planListLoad: false,
        planList: list.planList
      })
    }

  }

  async getLocation(movieId, cinemaId) {
    try {
      // Taro.getLocation({
      //   type: 'wgs84',
      //   success: async (res) => {
      //     const city = await location.getLocationCity(res.longitude, res.latitude)
      //     Taro.setStorageSync("ML", {lng: res.longitude, lat: res.latitude})
      //     if (city) {
      //       await this.openData(city.area_name, {lng: res.longitude, lat: res.latitude}, movieId, cinemaId)
      //     } else {
      //       Taro.hideLoading()
      //     }
      //   },
      //   fail: () => {
      //     Taro.showModal({
      //       title: '提示',
      //       content: '小程序需要定位权限, 请打开使用我的地理位置',
      //       success: (res) => {
      //         if (res.confirm) {
      //           Taro.openSetting()
      //         } else if (res.cancel) {
      //           Taro.switchTab({
      //             url: '/pages/index/index'
      //           })
      //         }
      //       }
      //     })
      //   }
      // })
      location.getLocation().then(async (res: any) => {
        if (res == null) {
          console.log('不是微信浏览器');
        } else {
          const city = await location.getLocationCity(res.longitude, res.latitude)
          Taro.setStorageSync("ML", {lng: res.longitude, lat: res.latitude})
          if (city) {
            await this.openData(city.area_name, {lng: res.longitude, lat: res.latitude}, movieId, cinemaId)
          } else {
            Taro.hideLoading()
          }
        }
      });
    } catch (e) {
      Taro.showModal({
        title: '提示',
        content: '您需要开启手机的GPS定位, 才能为您匹配精准的自提点信息',
        success: (res) => {
        }
      })
    }
  }

  async openData(str, ML, movieId, cinemaId) {
    const that = this
    const ret = await http.MGet(MOVIE_CITY, {})
    if (ret) {
      let val = {}
      const list = ret
      list.map(item => {
        if (str && str.indexOf(item.city_name) > -1) {
          val = {region_id: item.city_id, area_name: item.city_name}
        }
      })
      Taro.hideLoading()
      if (val.region_id) {
        Taro.setStorageSync("Mlocation", val)
        const isLogin = await user.checkLogin()
        if (!isLogin) {
          this.setState({isLogin, location: val, ML, cinemaId, movieId})
          user.jumpLogin()
          return
        } else {
          this.setState({isLogin, location: val, ML, cinemaId, movieId})
        }
        await this.getInfo(cinemaId, val.region_id, ML)
        const ret = await this.getList(cinemaId, val.region_id, ML, movieId)
        if (ret) {
          let thisIndex = 0
          ret.movieList.map((item, index) => {
            if (item.std_id == movieId) {
              thisIndex = index
            }
          })
          this.setState({
            movieList: ret.movieList,
            thisIndex,
          })
        }
      } else {
        Taro.showToast({
          title: '获取城市失败！请手动定位',
          icon: 'none',
          duration: 2000,
        })
        setTimeout(function () {
          Taro.navigateTo({
            url: "/other/select-city/movie-city"
          })
        }, 2000)
      }
    } else {
      Taro.hideLoading()
      Taro.navigateTo({
        url: "/other/select-city/movie-city"
      })
    }
  }

  GetDateStr(AddDayCount) {
    const dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount);
    const num = dd.getDay(dd);
    let week = "";
    switch (num) {
      case 0:
        week = "周日";
        break;
      case 1:
        week = "周一";
        break;
      case 2:
        week = "周二"
        break;
      case 3:
        week = "周三"
        break;
      case 4:
        week = "周四"
        break;
      case 5:
        week = "周五"
        break;
      case 6:
        week = "周六"
        break;
      default:
        break;
    }
    ;
    if (AddDayCount == 0) {
      week = "今天"
    } else if (AddDayCount == 1) {
      week = "明天"
    }
    const y = dd.getFullYear()
    const m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);
    const d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
    return {showDate: week + m + "月" + d + "日", paramDate: y + '-' + m + '-' + d};
  }

  async swiperChange(e) {
    const {cinemaId, movieList, dateAry, tabsIndex} = this.state
    const ML = Taro.getStorageSync('ML')
    const location = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
    const thisIndex = process.env.TARO_ENV != 'h5' ? e.detail.current : e
    Taro.showLoading({title: "加载中", mask: true})
    const list = await http.MGet(MOVIE_MOVIES, {
      type: 1,
      cityId: location.region_id,
      lng: ML.lng,
      lat: ML.lat,
      cinemaId,
      movieId: movieList[thisIndex].std_id
    })
    let newtabsIndex = 0
    const dateA = list.dateList
    if (dateAry && dateAry.length > 0 && dateA.length > 0) {
      const date = dateAry[tabsIndex]
      dateA.map((item, index) => {
        if (date.showDate == item.showDate && date.paramDate == item.paramDate) {
          newtabsIndex = index
        }
      })
    }

    this.setState({
      thisIndex,
      tabsIndex: newtabsIndex,
      dateAry: dateA
    })
    if (dateA.length > 0) {
      await this.getData(cinemaId, movieList[thisIndex].std_id, dateA[newtabsIndex].paramDate)
    } else {
      this.setState({
        movieId: movieList[thisIndex].std_id,
        loadMoreStatus: 'noMore',
        planListLoad: false,
        planList: []
      })
    }
    Taro.hideLoading()
  }

  async cheakDate(index) {
    setTimeout(() => {
      const {cinemaId, movieList, dateAry, thisIndex} = this.state
      this.setState({
        tabsIndex: index
      }, () => {
        this.getData(cinemaId, movieList[thisIndex].std_id, dateAry[index].paramDate)
      })
    }, 300)

  }

  timeEnd(date, time) {
    const d = new Date(new Date(date).getTime() + Number(time) * 60 * 1000)
    const hours = d.getHours()
    const minutes = d.getMinutes()
    return (hours < 10 ? ('0' + hours) : hours) + ':' + (minutes < 10 ? ('0' + minutes) : minutes)
  }

  onOther(e) {
    //console.log(e)
  }

  buy(item) {
    const {cinemaId, movieList, thisIndex} = this.state
    item['duration'] = movieList[thisIndex].duration
    item['movieId'] = cinemaId
    item['movieName'] = movieList[thisIndex].name
    item['poster'] = movieList[thisIndex].poster
    item['language'] = movieList[thisIndex].language
    //console.log(movieList[thisIndex])
    Taro.setStorageSync("seats", item)
    Taro.navigateTo({
      url: '/movie/seats?planId=' + item.plan_id + '&cid=' + cinemaId + '&featureAppNo=' + item.featureAppNo + '&std_id=' + movieList[thisIndex].std_id
    })
  }

  async navigateOut(latitude, longitude) {
    lxH5Wx.navigation(latitude, longitude)
  }

  onShareAppMessage() {
    const {imageUrl, shareName, movieId, cinemaId} = this.state
    return {
      path: '/movie/Minfo?id=' + cinemaId + (movieId ? '&mid=' + movieId : '') + '&' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
      title: shareName ? shareName : '想看特价电影，就来购吧！',
      imageUrl
    };
  }

  async onGetPoster() {
    Taro.showLoading({title: '获取海报中...'});
    const {movieId, cinemaId, movieList, thisIndex, tempSellerId} = this.state
    const shareParams = await user.getMovieSellerParams(tempSellerId)
    const mid = movieId ? movieId : ''/* '_'+ */
    const name = movieList[thisIndex].name
    const poster = await getMoviePoster({
      path: 'movie/Cinfo',
      scene: cinemaId + '_' + shareParams,
      pageType: 'detail',
      name,
      tempSellerId,
      cinemaId,
      movieId: movieId || ''
    }, movieList[thisIndex].poster)
    Taro.hideLoading();
    if (poster) {
      Taro.navigateTo({url: '/distributor/poster/poster?url=' + poster.url})
    } else {
      Taro.showToast({title: '获取海报失败！', icon: 'none'})
    }
  }

  showIndex(thisIndex) {
    this.setState({thisIndex})
  }

  showIndexH5(thisIndex) {
    const scrollview = document.querySelector('.scrollview')
    const scrollviewItem = document.querySelector('.scrollview-item')
    scrollview.scrollTo({
      top: 0,
      left: scrollviewItem.clientWidth * thisIndex,
      behavior: "smooth"
    })
    // this.setState({thisIndex})
  }

  h5Scroll = debounce((e) => {
    const that = this
    const left = e[0].detail.scrollLeft
    const scrollview = document.querySelector('.scrollview')
    const scrollviewItem = document.querySelector('.scrollview-item')
    const thisIndex = (left % scrollviewItem.clientWidth) > (scrollviewItem.clientWidth / 2) ? Math.ceil(left / scrollviewItem.clientWidth) : Math.floor(left / scrollviewItem.clientWidth)
    //console.log(thisIndex)
    scrollview.scrollTo({
      top: 0,
      left: scrollviewItem.clientWidth * thisIndex,
      behavior: "smooth"
    })
    that.setState({thisIndex})
    this.swiperChange(thisIndex)
  }, 300)

  render() {
    const {searchBarTop, dateAry, planList, movieList, thisIndex, tabsIndex, info, planListLoad, loadMoreStatus} = this.state
    return (
      <View className='movieInfo'>
        {process.env.TARO_ENV != 'h5' && <View className='head-bg' style={`height: ${searchBarTop}Px;background:#fff`}>
          <InfoHeaderBar backgroundColor='#fff' color='#696969' selectedColor='#ffa013' index={1}></InfoHeaderBar>
        </View>}
        <View className='cinfo-box'>
          <Skeleton loading={planListLoad} title row={2} action>
            <View className='cinfo-add' onClick={this.navigateOut.bind(this, Number(info.lat), Number(info.lng))}>
              <View className='cinfo-add-name'>
                <View className='name'>{info.name}</View>
                <View className='desc'>{info.address}</View>
              </View>
              <View className='cinfo-add-icon'><AtIcon value='chevron-right' size='20' color='#bbb'></AtIcon></View>
              <View className='shu'></View>
              <View className='cinfo-add-icon'><AtIcon prefixClass='car' value='icondizhi' size='20'></AtIcon></View>
            </View>
          </Skeleton>
          <View className='cinfo-list'>
            {process.env.TARO_ENV === 'weapp' ? <Swiper
              className='test-x'
              displayMultipleItems={5}
              indicatorDots={false}
              duration={100}
              current={thisIndex}
              onChange={this.swiperChange.bind(this)}
            >
                <SwiperItem>
                  <View className='demo-text'></View>
                </SwiperItem>
                <SwiperItem>
                  <View className='demo-text'></View>
                </SwiperItem>
                {movieList && movieList.length > 0 && movieList.map((item, index) =>
                  <SwiperItem key={index}>
                    <View className={thisIndex == index ? 'demo-text on' : 'demo-text'}
                      onClick={this.showIndex.bind(this, index)}
                    >
                      <Image className='poster' src={RESOURCE_URL + item.poster} mode='aspectFill'></Image>
                      <View className='movie-name'>{item.name}</View>
                    </View>
                  </SwiperItem>
                )}
                <SwiperItem>
                  <View className='demo-text'></View>
                </SwiperItem>
                <SwiperItem>
                  <View className='demo-text'></View>
                </SwiperItem>
              </Swiper>
              :
              <ScrollView
                className='scrollview h5'
                onScroll={this.h5Scroll.bind(this)}
                scrollX
              >
                <View className='scrollview-item'><View className='demo-text'></View></View>
                <View className='scrollview-item'><View className='demo-text'></View></View>
                {movieList && movieList.length > 0 && movieList.map((item, index) =>
                  <View className='scrollview-item' key={index} onClick={this.showIndexH5.bind(this, index)}><View
                    className={thisIndex == index ? 'demo-text on' : 'demo-text'}
                  >
                    <Image className='poster' src={RESOURCE_URL + item.poster} mode='aspectFill'></Image>
                    <Text className='titleName'>{item.name}</Text>
                  </View>
                  </View>
                )}
                <View className='scrollview-item'><View className='demo-text'></View></View>
                <View className='scrollview-item'><View className='demo-text'></View></View>
              </ScrollView>
            }
          </View>
        </View>
        <View className='cinema-box' style='margin-top:0 !important'>
          {dateAry.length > 0 &&
          <ScrollView scrollX enable-flex className='subNav'>
            <View className='info-date'>
              {dateAry.map((item, index) =>
                <View className={index == tabsIndex ? "info-date-item on" : "info-date-item"} key={item.paramDate}
                  onClick={this.cheakDate.bind(this, index)}
                >
                  {item.showDate}
                </View>
              )}
            </View>
          </ScrollView>
          }
        </View>
        <Skeleton loading={planListLoad} row={2} rowHeight={150}>
          <Block>
            {planList && planList.length > 0 ?
              <View className='sessions-box'>
                {planList.map((item, index) =>
                  <View className='sessions-item' key={index}>
                    <View className='sessions-item-time-box'>
                      <View className='sessions-item-time'>{item.start_time}</View>
                      <View className='sessions-item-time-end'>{item.end_time}散场</View>
                    </View>
                    <View className='sessions-item-hall-box'>
                      <View className='sessions-item-hall'>
                        原版
                        {item.plan_type}</View>
                      <View className='sessions-item-hall-num'>{item.hall_name}</View>
                    </View>
                    <View className='sessions-item-pay-box'>
                      {Number(item.market_price) >= Number(item.userPrice) &&
                      <Block>
                        <View className='sessions-item-pay-top'>
                          <Text className='old'>￥{item.market_price}</Text>
                          <Text className='red'><Text style='font-size:24rpx'>￥</Text>{item.userPrice}</Text>
                        </View>
                        <View className='sessions-item-pay-center'>
                          {!!item.secondSellerMoney &&
                          <Text>上级佣金:<Text className='red'>￥{item.secondSellerMoney} </Text></Text>}
                          {!!item.firstSellerMoney &&
                          <Text> 佣金:<Text className='red'>￥{item.firstSellerMoney}</Text></Text>}
                        </View>
                        {(Number(item.market_price) - Number(item.userPrice)) > 0 &&
                        <View className={`sessions-item-pay-bottom ${process.env.TARO_ENV}`}>
                          <Text>直降</Text><Text>￥{(Number(item.market_price) - Number(item.userPrice)).toFixed(2)}</Text>
                        </View>
                        }
                      </Block>
                      }
                    </View>
                    <View onClick={this.buy.bind(this, item)} className='sessions-item-buy'>购票</View>
                  </View>
                )}

              </View>
              :
              <View className='sessions-box-none'>
                <AtLoadMore status={loadMoreStatus} noMoreText='暂无场次' moreBtnStyle='border:none;'
                  moreText='加载更多'
                ></AtLoadMore>
              </View>
            }
          </Block>
        </Skeleton>
        <View className='sharebox' onClick={this.onGetPoster.bind(this)}><Image
          src={RESOURCE_URL + "/resources/weapp/images/mshare.png"}
        />分享好友</View>
      </View>
    )
  }
}

export default Cinfo as ComponentClass<PageOwnProps, PageState>
